package com.example.run_game;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Achievement
{
	public int id;
	public String name;
	public String dateUnlocked;
	private Context context;
	private SoundManager sounds;
	AssetManager am;
	
	Achievement(int id, String name, String dateUnlocked, Context rungui)
	{
		this.id = id;
		this.name = name;
		this.context = rungui;
		am = context.getAssets();
		this.sounds = new SoundManager(context,am);
		if(dateUnlocked == null)
			this.dateUnlocked = "";
		else
			this.dateUnlocked = dateUnlocked;
	}

	public void testInGame(Player player, double altGained, double speedOfRun, long timeOfRun, double distanceOfRun, Checkpoint[] allCkps, int weatherCode)
	{
		switch(id)
		{
			case 1:
				testEverUpwards(player, altGained); break;
			case 2:
				testSpeedDemon(speedOfRun, timeOfRun); break;
			case 3:
				testEnduranceMaster(player, timeOfRun); break;
			case 4:
				testIWouldWalk(player, distanceOfRun); break;
			case 7:
				testExplorer(allCkps); break;
			case 8:
				testStormRunner(weatherCode); break;
			case 9:
				testTheIcemanRunneth(weatherCode); break;	
		}		
	}
	
	public void testEndGame()
	{
		Log.d("GAME: ", "Testing achievement id " + id);
		ArrayList<HashMap<String,String>> rh = readHistory();
		switch(id)
		{
			case 5:
				testConstantImprover(rh); break;
			case 6:
				//testRegularRunner(rh); 
				break;
			case 10:
				testFirstRun(); break;
		}		
	}
	

	private void testFirstRun()
	{
		Log.d("GAME: ", "Test First Run");
		achievementUnlocked();		
	}

	private void testTheIcemanRunneth(int weatherCode)
	{
		if(		weatherCode == 13 ||
				weatherCode == 14 ||
				weatherCode == 15 ||
				weatherCode == 16 ||
				weatherCode == 17 ||
				weatherCode == 18 ||
				weatherCode == 25 ||
				weatherCode == 41 ||
				weatherCode == 42 ||
				weatherCode == 43 ||
				weatherCode == 46)
		achievementUnlocked();	
	}

	private void testStormRunner(int weatherCode)
	{
		if(		weatherCode == 8 ||
				weatherCode == 9 ||
				weatherCode == 10 ||
				weatherCode == 11 ||
				weatherCode == 12 ||
				weatherCode == 37 ||
				weatherCode == 38 ||
				weatherCode == 39 ||
				weatherCode == 40 )
		achievementUnlocked();			
	}

	private void testExplorer(Checkpoint[] allCkps)
	{
		boolean clearedAll = true;
		for(int i=0; i<allCkps.length; i++)
			if(allCkps[i].counter == 0)
				clearedAll = false;	
		if(clearedAll)
			achievementUnlocked();
	}

	private void testIWouldWalk(Player player, double distanceOfRun)
	{
		double totalDistance = player.getTotalDistance() + distanceOfRun;
		if(totalDistance > 804*1000)
			achievementUnlocked();		
	}

	private void testSpeedDemon(double speedOfRun, long timeOfRun)
	{
		if(speedOfRun > 3.5 && timeOfRun > 3600)
			achievementUnlocked();
	}

	private void testEnduranceMaster(Player player, long timeOfRun)
	{
		long totalTime = player.getTotalTime() + timeOfRun;
		if(totalTime > 3600*20)
			achievementUnlocked();		
	}

	private void testEverUpwards(Player player, double altGained)
	{
		double totalHeight = player.getTotalAltGained() + altGained;
		if(totalHeight > 10000)
			achievementUnlocked();		
	}

	private void testConstantImprover(ArrayList<HashMap<String, String>> rh)
	{
		// TODO Jon, data mine please out of run history
		
	}

	private void testRegularRunner(ArrayList<HashMap<String, String>> rh)
	{
		ArrayList<Date> neededDates = new ArrayList<Date>();
		Date d = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		for (int i = 0; i < 7; i++)
		{
			c.add(Calendar.DATE, -1);
			c.set(	c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH), 
					0, 0, 0);
			Date dt = c.getTime();
			neededDates.add(dt);
		}
		for (int i = 0; i <rh.size(); i++)
		{
			System.out.println("i="+i+" hashmap:");
			for (Entry<String,String> e : rh.get(i).entrySet())
			{
				System.out.println("\tkey: "+e.getKey()+" value: "+e.getValue());
			}
			long time 		= Long.parseLong(rh.get(i).get(RunHistory.KEY_TIME));
			double dist 	= Double.parseDouble(rh.get(i).get(RunHistory.KEY_DISTANCE).replaceAll("km",""));
			Date date = new Date(time);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(cal.get(Calendar.YEAR), 
					cal.get(Calendar.MONTH), 
					cal.get(Calendar.DAY_OF_MONTH), 
					0, 0, 0);
			for(int j=0; i < neededDates.size(); i++)
			{
				if (cal.getTime().getTime() == neededDates.get(j).getTime())
				{
					neededDates.remove(j);
					break;
				}
			}
		}
		if (neededDates.size() == 0)
			achievementUnlocked();
	}
	
	private ArrayList<HashMap<String,String>> readHistory()
	{
		ArrayList<HashMap<String, String>> historyList = new ArrayList<HashMap<String, String>>();
		 
        XMLParser parser = new XMLParser();
        FileInputStream f;
		StringBuffer indexXml = new StringBuffer("");
       
        try
		{
			f = Achievement.this.context.openFileInput("RunHistory");
			int ch;
			while ((ch = f.read()) != -1)
			{
				indexXml.append((char)ch);
			}
			//DO PARSING XML THING
			Document doc = parser.getDomElement(indexXml.toString()); // getting DOM element
	        
			NodeList nl = doc.getElementsByTagName(RunHistory.KEY_RUN);
	        // looping through all song nodes &lt;song&gt;
	        for (int i = 0; i < nl.getLength(); i++) {
	            // creating new HashMap
	            HashMap<String, String> map = new HashMap<String, String>();
	            Element e = (Element) nl.item(i);
	            // adding each child node to HashMap key =&gt; value
	            map.put(RunHistory.KEY_ID, parser.getValue(e, RunHistory.KEY_ID));
	            map.put(RunHistory.KEY_START, parser.getValue(e, RunHistory.KEY_START));
	            map.put(RunHistory.KEY_DISTANCE, parser.getValue(e, RunHistory.KEY_DISTANCE));
	            map.put(RunHistory.KEY_TIME, parser.getValue(e, RunHistory.KEY_TIME));
	 
	            // adding HashList to ArrayList
	            historyList.add(map);
	        }
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
        return historyList;
	}
	
	
	private void achievementUnlocked()
	{		
		//Log.d("GAME: ", "Date Unlocked "+ dateUnlocked);
		String[] tracks = {""};

		if(dateUnlocked.equals(""))
		{
			SimpleDateFormat format =  new SimpleDateFormat("dd/MM/yyyy");
			dateUnlocked =   format.format(new Date().getTime());	
			Log.d("GAME:", "Achievement Unlocked: "+name);
			Toast.makeText(context, "Achievement Unlocked: "+name ,Toast.LENGTH_SHORT).show();
			tracks[0] = "achievement_twinkle.mp3";
			sounds.playSound(tracks);
			DbManager db = new DbManager(context);
			db.saveSingleAchievement(this);
		}
	}
}
